/*
 *
 * SimplePCR1000 (Qt4) Version 1.0.x
 * Copyright (C) 2011  Tyler H. Jones (me@tylerjones.me)
 * http://sourceforge.net/p/simplepcr1000/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


/*
#define S_SCAN_IVAL "ScannerInterval"
#define S_DELAY_IVAL "DelayInterval"
#define S_DATARATE "DataRate"
#define S_STARTHIDDEN "HideOnStartup"
#define S_STARTON "StartPowerOn"
#define S_CHANNOTIF "ChannelNotifs"
*/

#include "common.h"
#include "settingsdialog.h"
#include "ui_settingsdialog.h"

SettingsDialog::SettingsDialog(QWidget *parent, Database *ParentDB) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    DB = ParentDB;
    this->blockSignals(false);

    btnCancel = ui->btnboxSettings->addButton(QDialogButtonBox::Cancel);
    btnOK = ui->btnboxSettings->addButton(QDialogButtonBox::Ok);
    btnRestoreDefaults = ui->btnboxSettings->addButton(QDialogButtonBox::RestoreDefaults);

    createActions();
    LoadSettings();
}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}

/*********************************************************************
** Declare slots function
**********************************************************************/

void SettingsDialog::createActions() {
    connect(ui->btnBackupDB,SIGNAL(clicked()),this,SLOT(clickBackupDB()));
    connect(btnCancel,SIGNAL(clicked()),this,SLOT(clickCancel()));
    connect(btnOK,SIGNAL(clicked()),this,SLOT(clickOK()));
    connect(btnRestoreDefaults,SIGNAL(clicked()),this,SLOT(clickRestoreDefaults()));
    connect(ui->btnResetDB,SIGNAL(clicked()),this,SLOT(clickResetDB()));
    connect(ui->btnRestoreDB,SIGNAL(clicked()),this,SLOT(clickRestoreDB()));
    connect(ui->btnTestPort,SIGNAL(clicked()),this,SLOT(changeTestPort()));
    connect(ui->cboPorts,SIGNAL(currentIndexChanged(QString)),this,SLOT(changedSelectedPort(QString)));
}

/*********************************************************************
** Settings loading/saving functions
**********************************************************************/

void SettingsDialog::LoadSettings() {
    setupDatabaseTab();
    setupGeneralTab();
    setupAdvancedTab();
    setupConnectionTab();
}

void SettingsDialog::SaveSettings() {
    SET.set(S_CHANNOTIF, ui->chkChanNotif->isChecked());
    SET.set(S_STARTON, ui->chkRadioPower->isChecked());
    SET.set(S_AUTOSTART, ui->chkRunAtStartup->isChecked());
    SET.set(S_STARTHIDDEN, ui->chkStartMinimized->isChecked());

    if(ui->cboPorts->currentText() == "Custom...") {
        SET.set(S_PORT, ui->txtCustomPort->text());
    } else {
        SET.set(S_PORT, ui->cboPorts->currentText());
    }
    SET.set(S_DATARATE, ui->cboDataRate->currentText().toInt());

    SET.set(S_SCAN_IVAL, ui->txtScanInt->text());
    SET.set(S_DELAY_IVAL, ui->txtDelayInt->text());

    emit ReapplyConfig();
    this->close();
}

/*********************************************************************
** Window setup functions
**********************************************************************/

void SettingsDialog::setupDatabaseTab() {
    QString dir = QDir::homePath();
#ifdef Q_WS_X11
    ui->txtDBPath->setText(dir + "\\"APP_DIR"\\"APP_DBFILE);
#else
    ui->txtDBPath->setText(dir + "/"APP_DIR"/"APP_DBFILE);
#endif
    ui->lblDBVersion->setText("Current");
    ui->lblScanDBRows->setText(QString::number(DB->ChannelCount()));
}

void SettingsDialog::setupGeneralTab() {
    ui->chkChanNotif->setChecked(SET.get(S_CHANNOTIF).toBool());
    ui->chkRadioPower->setChecked(SET.get(S_STARTON).toBool());
    ui->chkRunAtStartup->setChecked(SET.get(S_AUTOSTART).toBool());
    ui->chkStartMinimized->setChecked(SET.get(S_STARTHIDDEN).toBool());
}

void SettingsDialog::setupAdvancedTab() {
    ui->txtDelayInt->setText(SET.get(S_DELAY_IVAL).toString());
    ui->txtScanInt->setText(SET.get(S_SCAN_IVAL).toString());
}

void SettingsDialog::setupConnectionTab() {
    ui->cboPorts->addItems(COM.ComPortValues);
    if(COM.ComPortValues.contains(SET.get(S_PORT).toString(),Qt::CaseInsensitive)) {
        ui->cboPorts->setCurrentIndex(COM.ComPortValues.indexOf(SET.get(S_PORT).toString()));
        ui->txtCustomPort->setEnabled(false);
    } else {
        ui->cboPorts->setCurrentIndex(COM.ComPortValues.indexOf("Custom..."));
        ui->txtCustomPort->setEnabled(true);
        ui->txtCustomPort->setText(SET.get(S_PORT).toString());
    }
    ui->cboDataRate->setCurrentIndex(COM.DataRates.indexOf(SET.get(S_DATARATE).toString()));
}

/*********************************************************************
** Slot functions
**********************************************************************/

void SettingsDialog::changedSelectedPort(QString val) {
    if(val.trimmed() == "Custom...") {
        ui->txtCustomPort->setEnabled(true);
        ui->txtCustomPort->setText(SET.get(S_PORT).toString());
        ui->txtCustomPort->setFocus();
    } else {
        ui->txtCustomPort->setEnabled(false);
        ui->txtCustomPort->setText("Custom Port...");
    }
}

void SettingsDialog::clickRestoreDefaluts() {
    int res = QMessageBox::question(0, MB_ConfirmRestoreDefaults_T, MB_ConfirmRestoreDefaults_B, QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape, QMessageBox::NoButton);
    if(res != QMessageBox::Yes) {
        return;
    } else {
        SET.RestoreDefaults();
        //LoadSettings();
        emit ReapplyConfig();
        return;
    }
}

void SettingsDialog::clickCancel() {
    this->close();
}

void SettingsDialog::clickOK() {
    SaveSettings();
    this->close();
}

void SettingsDialog::clickTestPort() {

}

void SettingsDialog::clickResetDB() {
    int res = QMessageBox::question(0, MB_ConfirmResetDB_T, MB_ConfirmResetDB_B, QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape, QMessageBox::NoButton);
    if(res != QMessageBox::Yes) {
        return;
    } else {
        QString filename = QString(QDir::homePath() + "/" + APP_DIR + "/" + APP_DBFILE);
        QFile *dbfile = new QFile(filename);
        if(!dbfile->exists()) {
            qDebug() << "clickResetDB: The DB file is already deleted or missing! '" + filename + "'";
            return;
        }
        DB->Disconnect();
        dbfile->remove();
        dbfile->close();
        DB->Connect();
    }
}

void SettingsDialog::clickBackupDB() {
    int res = QMessageBox::question(0, MB_ConfirmRestoreDB_T, MB_ConfirmRestoreDB_B, QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape, QMessageBox::NoButton);
    if(res != QMessageBox::Yes) {
        return;
    } else {
        QString dbpath = QString(QDir::homePath() + "/" + APP_DIR + "/" + APP_DBFILE);
        QString dbbkppath = QString(QDir::homePath() + "/" + APP_DIR + "/" + APP_DBFILE_BKP);

        QFile *dbfile = new QFile(dbpath);
        if(!dbfile->exists()) {
            qDebug() << "clickBackupDB: The DB file is already deleted or missing! '" + dbpath + "'";
            return;
        }
        QFile *dbbkpfile = new QFile(dbbkppath);
        if(!dbbkpfile->exists()) { dbbkpfile->remove(); }
        dbbkpfile->close();
        if(dbfile->copy(dbbkppath)) {
            QMessageBox::information(0, MB_DBBackupSuccess_T, MB_DBBackupSuccess_B, QMessageBox::Ok);
            dbfile->close();
            return;
        } else {
            QMessageBox::critical(0, MB_DBBackupFailed_T, MB_DBBackupFailed_B, QMessageBox::Ok);
            dbbkpfile->close();
            return;
        }
    }
}

void SettingsDialog::clickRestoreDB() {
    int res = QMessageBox::question(0, MB_ConfirmRestoreDB_T, MB_ConfirmRestoreDB_B, QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape, QMessageBox::NoButton);
    if(res != QMessageBox::Yes) {
        return;
    } else {
        QString dbpath = QString(QDir::homePath() + "/" + APP_DIR + "/" + APP_DBFILE);
        QString dbbkppath = QString(QDir::homePath() + "/" + APP_DIR + "/" + APP_DBFILE_BKP);

        QFile *dbfile = new QFile(dbpath);
        QFile *dbbkpfile = new QFile(dbbkppath);

        if(dbfile->exists()) { dbfile->remove(); }
        if(!dbbkpfile->exists()) {
            QMessageBox::critical(0, MB_DBBackupMissing_T, MB_DBBackupMissing_B, QMessageBox::Ok);
            qDebug() << "clickRestoreDB: The backup DB file is deleted or missing! '" + dbbkppath + "'";
            return;
        }
        dbbkpfile->close();
        DB->Disconnect();
        if(dbfile->copy(dbbkppath)) {
            dbfile->remove();
            dbfile->close();
            DB->Connect();
        } else {
            QMessageBox::critical(0, MB_DBRestoreFailed_T, MB_DBRestoreFailed_B, QMessageBox::Ok);
            return;
        }

    }
}
